package com.skytech.component.crawler.quartz;


import com.skytech.component.crawler.parse.*;
import com.skytech.component.crawler.scratch.*;
import com.skytech.component.crawler.task.NewsListPageOperation;
import com.skytech.component.crawler.task.TaskManager;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;


@Configuration
@Component
@EnableScheduling
public class UpdateCronTask {

    @Autowired
    private TargetRulesDAO targetRulesDAO;
    @Value("${chrome.driver.path}")
    private String driverPath;

    @Autowired
    private CrawlerUrlDAO crawlerUrlDAO;

    @Autowired
    private ParserLoader parserLoader;

    @Autowired
    private SaveDataToES saveData;

    @Autowired
    private TaskStatusDAO taskStatusDAO;

    private TaskManager taskManager;

    private static final Logger logger= LoggerFactory.getLogger(UpdateCronTask.class);


    public void startOneTask(String id) {
        //改变任务状态
        TaskStatus taskStatus=new TaskStatus();
        if(!taskStatusDAO.findAllByRuleId(id).isEmpty()){
            if(taskStatusDAO.findAllByRuleId(id).get(0).getStatus().equals("STOP")||taskStatusDAO.findAllByRuleId(id).get(0).getStatus().equals("INIT")){
                //设置任务状态
                taskStatus=taskStatusDAO.findAllByRuleId(id).get(0);
                taskStatus.setStatus(State.RUNNING.toString());
                taskStatusDAO.save(taskStatus);
                //开始任务
                startTask(id);
                //任务执行完成
                taskStatus.setStatus(State.STOP.toString());
                taskStatusDAO.save(taskStatus);
            }else{
                logger.error("{},任务正在进行",id);
            }
        }else{
            taskStatus.setId(UUID.randomUUID().toString());
            taskStatus.setRuleId(id);
            taskStatus.setStatus(State.RUNNING.toString());
            taskStatusDAO.save(taskStatus);

            startTask(id);

            taskStatus.setStatus(State.STOP.toString());
            taskStatusDAO.save(taskStatus);
        }

    }


    public void startTask(String id){
        logger.info("{},任务开始！",id);
        List<String> ids = Arrays.asList(id);
        List<TargetRules> ruleList = targetRulesDAO.findAll().stream().filter(l -> ids.contains(l.getId())).collect(Collectors.toList());
        taskManager = new TaskManager(ruleList,driverPath,new NewsListPageOperation(crawlerUrlDAO));
        taskManager.start();
        //解析
        parserLoader.load(id,new SeleniumDownloader(driverPath),saveData);
    }




    }




